package com.wlf.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.IdentityHashMap;
import java.util.concurrent.TimeUnit;

public class MyServer {
    public static void main(String[] args) throws Exception{
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workerGroup).
                    channel(NioServerSocketChannel.class).
                    //在boosGroup 增加一个日志处理器
                    handler(new LoggingHandler(LogLevel.INFO)).
                    childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //加入一个netty提供的IdleStateHandler
                            /**
                             * 1,IdleStateHandler 是netty提供的处理空闲状态的处理器
                             * 2，
                             * readerIdleTime：表示多长时间没有读，就会发送一个心跳检测包，检测是否还是连接的状态
                             * writerIdleTime：表示多长时间没有写，就会发送一个心跳检测包，检测是否还是连接的状态
                             * allIdleTime：表示多长时间没有读写，就会发送一个心跳检测包，检测是否还是连接的状态
                             * 3，文档说明
                             * Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed
                             * read, write, or both operation for a while.
                             * 当 IdleStateEvent 触发后，就会传递给管道pipeline下一个Handler去处理，
                             * 通过调用下一个Handler 的userEventTrigger,在该方法中去处理
                             * IdleStateEvent 可能是读空闲/写空闲/读写空闲
                             */
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            //加入一个对空闲检测进一步处理的handler（自定义）
                            pipeline.addLast(new MyServerHandler());
                        }
                    });
                    //启动服务器
                    ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
                    channelFuture.channel().closeFuture().sync();
        }finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }
    }
}
